package com.loklok.code.confuse.ui;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.search.GlobalSearchScope;
import com.loklok.code.confuse.dto.GenerateCodeDto;
import com.loklok.code.confuse.model.ClassMetaData;
import com.loklok.code.confuse.model.FeignInterfaceInfo;
import com.loklok.code.confuse.util.*;
import com.loklok.code.confuse.extension.PathConfigSettingCache;
import com.loklok.code.confuse.model.CodePathConfig;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class GenerateDtoVoCodeDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JTextField classPrefixText;
    private JRadioButton voCodeRadio;
    private JRadioButton dtoCodeRadio;
    private JTextField vmCodeText;
    private JButton chooseVmBut;

    public GenerateDtoVoCodeDialog(AnActionEvent anActionEvent) {
        setContentPane(contentPane);
        setTitle("codeConfuse");
        setSize(800, 300);
        setLocation(600, 200);
        setModal(true);
        setResizable(true);
        getRootPane().setDefaultButton(buttonOK);


        PathConfigSettingCache state = PathConfigSettingCache.getInstance(anActionEvent.getProject());
        Project project = anActionEvent.getProject();
        if (state == null || state.getConfig() == null || state.getConfig().requiredFieldsEmpty()) {
            CommonUtil.configureMessageReminders(project);
            return;

        }
        CodePathConfig config = state.getConfig();

        chooseVmBut.addActionListener(actionEvent -> FilePackageChooseUtils.chooseFileAndSetPath(project, vmCodeText));

        buttonOK.addActionListener(e -> {

            if(StringUtils.isEmpty(classPrefixText.getText()) ||
                    !(voCodeRadio.isSelected() || dtoCodeRadio.isSelected()) || StringUtils.isEmpty(vmCodeText.getText())){
                Messages.showInfoMessage("类前缀和选择类型以及生成模板都是必填!", "Error");
                return;
            }
            backgroundTaskGenerateDtoVoCode(anActionEvent, project, config, voCodeRadio.isSelected());
            onOK();
        });
    }

    private void backgroundTaskGenerateDtoVoCode(AnActionEvent anActionEvent, Project project, CodePathConfig config, boolean isChooseVo) {
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "Generating Files", false) {
            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                indicator.setText("ConfuseCode plugin Generating files...");
                indicator.setFraction(0.0); // 初始化进度

                Path path = Paths.get(vmCodeText.getText());
                // 获取文件名
                String className = path.getFileName().toString().replace(".vm", "");
                ClassMetaData item = new ClassMetaData(className, className, isChooseVo ? ClassMetaDataTypeEnum.VO : ClassMetaDataTypeEnum.REQUEST, null);
                if (LocalFileUtils.isFileExist(project, config, item, classPrefixText.getText())) {
                    System.out.println("backgroundTaskGenerateDtoVoCode code file exists :" +  item.getClassName());
                    indicator.setFraction(1.0); // 完成进度
                    indicator.setText("ConfuseCode plugin File generation complete!");
                    Messages.showInfoMessage(project, "文件已存在", "提示");
                    return;
                }

                GenerateCodeDto generateCodeDto = VelocityUtils.generateDtoVoCode(config, vmCodeText.getText(), classPrefixText.getText(), isChooseVo);

                // 将整个文件写入操作调度到EDT线程执行
                ApplicationManager.getApplication().invokeLater(() -> {
                    LocalFileUtils.writeFile(anActionEvent, generateCodeDto.getFullPck(), generateCodeDto.getClassName(), generateCodeDto.getGenerateCode(), generateCodeDto.getFileType());
                });

                indicator.setFraction(1.0); // 完成进度
                indicator.setText("ConfuseCode plugin File generation complete!");
            }
        });
    }


    private void onOK() {
        // add your code here
        dispose();
    }
}
